﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using MarketPlace.Data;
using MarketPlace.Data.DomainModels;
using NHibernate;
using NHibernate.Cfg;
using MarketPlace.Data.ManagerObjects;

namespace MarketPlace.Data
{
    /// <summary>
    /// 客户身份工具类
    /// </summary>
    public static class ClientHelper
    {
        private static readonly string CurrentUserSessionKey = "LinLangCurrentUser";

        /// <summary>
        /// 合计在线用户数
        /// </summary>
        public static int OnlineUsers { get; set; }

        #region SetAuthUserInfo
        /// <summary>
        /// 重设会话中的当前用户信息
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static User SetAuthUserInfo(string username)
        {
            Check.AssertNotNullOrEmpty(username, "username");

            HttpSessionState Session = HttpContext.Current.Session;

            IManagerFactory managerFactory = new ManagerFactory();

            IUserManager userManager = managerFactory.GetUserManager();

            User user = userManager.GetUniqueByQuery("from User where username='" + username.ToLower() + "'");

            if (null != user)
            {
                Session[CurrentUserSessionKey] = user;

                return user;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region ActiveUser
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        public static User GetActiveUser()
        {
            HttpRequest req = HttpContext.Current.Request;

            if (!req.IsAuthenticated)
            {
                return null;
            }

            HttpSessionState Session = HttpContext.Current.Session;

            User cu = (User)Session[CurrentUserSessionKey];

            if (null == cu)
            {
                return SetAuthUserInfo(HttpContext.Current.User.Identity.Name);
            }
            else
            {
                return (User)cu;
            }
        }
        #endregion


        /// <summary>
        /// 移除会话中的身份信息
        /// </summary>
        public static void ClearUserSession()
        {
            HttpSessionState Session = HttpContext.Current.Session;

            Session.Remove(CurrentUserSessionKey);
        }
    }
}
